package com.geek.factory.service.strategy;
import com.qiniu.storage.Configuration;
import com.geek.factory.config.QiniuConfig;
import com.geek.factory.exception.FactoryException;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.UUID;

/**
 * 七牛云上传策略
 */
@Component("qiniu")
public class QiniuUploadStrategy implements UploadStrategy{
    private final QiniuConfig qiniuConfig;
    private Auth auth;
    private UploadManager uploadManager;
    private BucketManager bucketManager;

    @Autowired
    public QiniuUploadStrategy(QiniuConfig qiniuConfig){
        this.qiniuConfig = qiniuConfig;
    }

    @PostConstruct
    public void init(){
        //TODO 鉴权
        auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //创建上传对象
        uploadManager = new UploadManager(cfg);
        //创建Bucket空间对象
        bucketManager = new BucketManager(auth, cfg);
    }

    @Override
    public String uploadFile(MultipartFile file) {
        if (file!=null){
            String oldName = file.getOriginalFilename();
            if(StringUtils.hasLength(oldName) && oldName.lastIndexOf(".")>0){
                String newName = UUID.randomUUID()+oldName;

                //文件上传
                String token = auth.uploadToken(qiniuConfig.getBucket());
                String key = newName;
                try {
                    //TODO 上传
                    Response response = uploadManager.put(file.getInputStream(), key, token, null, null);
                    //解析上传成功的结果
                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                    //TODO 返回存储在七牛云上的外链地址
                    return qiniuConfig.getHostName()+"/"+putRet.key;
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    public boolean deleteFile(String url) {
        String fileName = url.replaceAll(qiniuConfig.getHostName()+"/" , "");
        try {
            if(fileName!=null){
                Response response = bucketManager.delete(qiniuConfig.getBucket(), fileName);
                if (response.statusCode == 200) {
                    return true;
                }
            }
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.out.println(fileName + "----删除失败----" + ex.code());
            throw new FactoryException(fileName + "----删除失败----" + ex.code());
        }
        return false;
    }
}
